<?php
/**
 * 获取每日考勤记录详情bll
 */
apf_require_class("Bll_BLL");
class Bll_Attendance_UserInfo extends BLL{


    /**
     * 批量根据工号获取入职日期
     * @param string $code 工号字符串
     * @return array 入职日期数组
     */
    public function get_enterdate_by_code( $code ){
        if( empty($code) ){
            return array();
        }
        $code = "'".str_replace(",", "','", mysql_escape_string($code))."'";
        //$sql = 'SELECT `code`,`enter_date` FROM user_info WHERE code IN('.$code.')';
        $where = ' code IN('.$code.') ';
        return $this->get_app_dao()->find_short($where, $order = null, $limit = 0, $offset = 0, $feild=array('code','enter_date'));
        //show( $this->get_app_dao()->find_by_sql($sql) );die;
    }


    /**
     * 根据用户ids获取用户信息
     *
     * @param mixed $ids
     * @access public
     * @return void
     */
    public function get_user_by_ids($ids) {
        $result = array();
        if(empty($ids)) {
            return $result;
        }
        if(is_array($ids)) {
            $result = $this->get_app_dao()->find_by_ids($ids);
        } else {
            $result[0] = $this->get_app_dao()->find_by_id($ids);
        }
        return $result;
    }

    /**
     * 根据条件获取用户信息
     *
     * @param mixed $ids
     * @access public
     * @return void
     */
    public function get_user_by_condition($where) {
        $result = array();
        if(empty($where)) {
            return $result;
        }
        $result = $this->get_app_dao()->find($where,'user_id asc',0,0);
        return $result;
    }

    /**
     * 获取用户在指定年月份的假信息,若未指定开始和结束时间，则默认时间范围为本月
     *
     * @param $ids 用户ids
     * @param $start 开始时间 em:2012-06-01
     * @param $end 结束时间 em:2012-07-01
     * @return array(leave_info=>array(请假信息),'belate_info'=>array(迟到信息),'trip_info'=>array(公出信息))
     */
    public function get_users_record($ids,$start = 0,$end = 0) {
        $result = array();
        if(empty($ids)) {
            return $result;
        }
        if(!is_array($ids)) {
            $ids = array($ids);
        }
        //未选定时间则默认为当月
        if(empty($start) || empty($end)) {
            $time = time();
            $month = date('m',$time);
            $start = date('Y-m-d',mktime(0,0,0,$month,1,date('Y',$time)));//本月开始
            $end = date('Y-m-d',mktime(0,0,0,$month+1,1,date('Y',$time))-86400);
        }
        $where = array();

        $in_list = implode(',',$ids);
        $where["user_id in ({$in_list}) and 1=?"] = '1';
        $where["start_time >= '{$start}' and end_time <= '{$end}' and 1=?"] = '1';
        //$rs = $this->get_leave_record_dao()->find_assoc($where);
        $sql = "select * from leave_record where user_id in ({$in_list}) and start_time >= '{$start}' and end_time <= '{$end}'";
        $rs = $this->get_leave_record_dao()->find_by_sql($sql);

        if(empty($rs)) {
            return $result;
        }

        $record_type_all = array('丧假','事假','产假','产前假','产检','婚假','年假','病假','请假','陪产假','施加');//请假类型 无餐补
        //带薪假不算
        $record_type = array('事假','病假','请假','施加');//请假类型
        $belate_type = array('迟到');//迟到类型
        $corptrip_type = array('公出');//公出类型
        $trip_type = array('出差');//出差类型
        $sj_type = array('事假','施加');
        $bj_type = array('病假');
        $nj_type = array('年假');
        $other_type = array('丧假','产假','产前假','产检','婚假','请假','陪产假');
        foreach($rs as $v) {
            //所有假期，算餐补要用到数据
            if(in_array($v['type'],$record_type_all) && $v['status']=='已批准') {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                $tmp['leave_msg'] = $start.'至'.$end;
                $tmp['leave_status'] = 8;
                $result['leave_info_all'][] = $tmp;
            }

            //请假条件 && 已批准
            if(in_array($v['type'],$record_type) && $v['status']=='已批准') {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                $tmp['leave_msg'] = $start.'至'.$end;
                $tmp['leave_status'] = 8;
                $result['leave_info'][] = $tmp;
            }
            //迟到 && 未批准
            if(in_array($v['type'],$belate_type) && $v['status']!='已批准') {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $result['belate_info'][] = $tmp;
            }
            //公出 && 已批准
            if(in_array($v['type'],$corptrip_type)) {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                if($v['status']=='已批准'){
                    $tmp['leave_status'] = 8;
                }elseif($v['status']=='未审核'){
                    $tmp['leave_status'] = 0;
                }
                $result['corptrip_info'][] = $tmp;
            }
            //出差 && 已批准
            if(in_array($v['type'],$trip_type) && $v['status']=='已批准') {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['leave_id'];
                $tmp['leave_time'] = $v['leave_time'];
                $result['trip_info'][] = $tmp;
            }
            //事假 && 已批准
            if(in_array($v['type'],$sj_type)) {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                if($v['status']=='已批准'){
                    $tmp['leave_status'] = 8;
                }elseif($v['status']=='未审核'){
                    $tmp['leave_status'] = 0;
                }
                $result['sj_info'][] = $tmp;
            }
            //病假 && 已批准
            if(in_array($v['type'],$bj_type)) {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['leave_id'];
                $tmp['leave_time'] = $v['leave_time'];
                if($v['status']=='已批准'){
                    $tmp['leave_status'] = 8;
                }elseif($v['status']=='未审核'){
                    $tmp['leave_status'] = 0;
                }
                $result['bj_info'][] = $tmp;
            }
            //年假 && 已批准
            if(in_array($v['type'],$nj_type)) {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                if($v['status']=='已批准'){
                    $tmp['leave_status'] = 8;
                }elseif($v['status']=='未审核'){
                    $tmp['leave_status'] = 0;
                }
                $result['nj_info'][] = $tmp;
            }
            //其它假 && 已批准
            if(in_array($v['type'],$other_type)) {
                $tmp = array();
                $tmp['user_id'] = $v['user_id'];
                $tmp['leave_id'] = $v['id'];
                $tmp['leave_time'] = $v['leave_time'];
                if($v['status']=='已批准'){
                    $tmp['leave_status'] = 8;
                }elseif($v['status']=='未审核'){
                    $tmp['leave_status'] = 0;
                }
                $result['oj_info'][] = $tmp;
            }
        }
        return $result;
    }

    /**
     * 根据时间点本月当天前的数据
     * access_date >= $start AND access_date <= $end
     * @param mixed $params
     * @access private
     * @return void
     */
    public function get_cd_kg($params) {
        $result = array();
        $cd = 0;//迟到天数
        $kg = 0;//旷工
        //如果用户未登录，返回空数组
        $uid = $params['uid'];
        $ym = $params['ym'];

        $y = substr($ym,0,4);
        $m = substr($ym,4,2);

        $dayinfo = getdate(mktime(0,0,0,$m+1,1,$y)-1);
        $m_lenght = $dayinfo['mday'];//当月最后一天

        $now_ym = date("Ym");
        if($now_ym == $ym){
            $m_lenght = date("d");//当月做特殊处理
        }
        elseif($now_ym < $ym  or !$uid){//大于当月的没有数据,无uid
            return array('cd'=>0,'kg'=>0);
        }

        //用户详情
        apf_require_class('Bll_Login_User');
        $user_bll = new Bll_Login_User;
        $uinfo = $user_bll->get_user_info_by_ids(array($uid));
        $uinfo = $uinfo[$uid];

        //TODO 增加当月离职和入职的特殊处理
        $enter_date = strtotime($uinfo['enter_date']);
        $dimission_date = strtotime($uinfo['dimission_date']);

        apf_require_class('Tools_Tools');

        $start = $ym."01";
        $end = $ym.$m_lenght;
        $te = mktime(0,0,0,$m,$m_lenght,$y);

        apf_require_class('Bll_Attendance_AccessDayRecord');
        $bll = new Bll_Attendance_AccessDayRecord();
        $list = $bll->get_my_attendance($uid,$start,$end);
        $leave_record = $list['allleaverecord'];unset($list['allleaverecord']);
        $first = $te;
        for($i = 0; $i < $m_lenght; $i++) {
            $each = mktime(0,0,0,date('m',$te),date('d',$te) - $i,date('Y',$te));

            if($enter_date >= $each){//入职在当月
                continue;
            }
            if($dimission_date <= $each and $uinfo['dimission_date'] != '0000-00-00 00:00:00'){
                continue;
            }

            $curr = date('Ymd',$each);
            //只开启上海
            if($uinfo['city_name'] != '上海') {
                return array();
                //continue;
            }
            $dowork = Tools_Tools::get_instance()->special_work_day();
            if($list[$curr]) {
                $result[] = $list[$curr];//有考勤记录的
                if($list[$curr]['start_work']>910 && $list[$curr]['start_work']<931){
                    if((date('w',$each) != 6 && date('w',$each) != 0) or in_array(date('Y-m-d',$each),$dowork)) {
                        $find = false;
                        foreach ($leave_record as $k => $v) {
                            //迟到了判断是否有请假，请假是否有批准
                            $ajust = mktime(9,11,0,date('m',$each),date('d',$each),date('Y',$each));
                            if($v['type']=="缺勤" or $v['type']=="迟到" or $v['type'] == '早退') {
                                $v['end'] += 86399;
                            }
                            if($ajust >= $v['start'] && $ajust <= $v['end'] && $v['status'] == '已批准') {
                                $find = true;
                                break;
                            }
                        }
                        if(!$find){
                            $cd++;
                        }
                    }
                }
            } else {
                $tmp = array();
                $tmp = array('month' => date('m',$each),
                        'day' => date('d',$each),
                        'week' => Tools_Tools::get_instance()->convert_chinese_week(date('w',$each))
                );
                //不为周末时的情况
                if((date('w',$each) != 6 && date('w',$each) != 0) or in_array(date('Y-m-d',$each),$dowork)) {
                    $holiday = Tools_Tools::get_instance()->each_year_holiday_country();
                    if(in_array(date('Y-m-d',$each),$holiday)) {
                    }
                    elseif(empty($leave_record)) {
                        //$tmp['status'][0] = array('id' => 999,'name' => '无考勤数据');
                        if(date('Ymd',$each) >= 20120701) {
                            $kg++;
                        }
                    } else {
                        $find =false;
                        foreach ($leave_record as $k => $v) {
                            $ajust = mktime(9,31,0,date('m',$each),date('d',$each),date('Y',$each));
                            if($v['type'] == '缺勤' or $v['type']=="迟到") {
                                $v['end'] += 86399;
                            }
                            if($ajust >= $v['start'] && $ajust <= $v['end'] && $v['status'] == '已批准') {
                                $find = true;
                                break;
                            }
                        }
                        if(!$find) {
                            if(date('Ymd',$each) >= 20120701) {
                                $kg++;
                            }
                        }
                    }
                }
            }
        }
        return array('cd'=>$cd,'kg'=>$kg);
    }



    public function get_all_users(){
        $sql = "select * from user_info where job_status<>'离职' and dimission_date='0000-00-00 00:00:00'";
        return $this->get_app_dao()->find_by_sql($sql);
    }

    /**
     * 搜索下属信息
     */
    public function search_user_record($where) {
        $result = array();
        if(empty($where['user_id'])) {
            return $result;
        }

    }
    /**
     * 是否有下属
     */
    public function has_subordinate($user_id){
        $result = array();
        $result = $this->get_orgRelation_dao()->find(array('superior_id'=>$user_id));
        if(!empty($result)){
            return true;
        }
        return false;
    }

    /*
    public function get_all_dtp_info(){
        $sql = "select * from deparetment ";
        return  $this->get_department_dao()->find_by_sql($sql);
    }*/

    /**
     * 获得用户角色ID 移植于 Bll_Login_User
     * @param unknown_type $code
     * @return string
     */
    public function get_user_role_id($code) {
        $result = '0';
        if(empty($code)) {
            return $result;
        }
        if(is_numeric($code)) {//根据用户user_id获得角色ID
            $rs = $this->get_user_role_dao()->find_by_id($code);
            if(!empty($rs)) {
                $result = $rs['role_id'];
            }
        }else {
            //获得用户信息
            $userinfo = $this->get_user_info($code);
            $user_id = (int)$userinfo['user_id'];
            if(!empty($user_id)) {
                $result = $this->get_user_role_id($user_id);
            }
        }
        return $result;
    }

    /**
     * 根据用户ids获取用户角色 移植于 Bll_Login_User
     * @param unknown_type $uids
     */
    public function get_user_role($uids) {
        $result = array();
        if(empty($uids)) {return $result;}
        if(!is_array($uids)) {
            $uids = array($uids);
        }
        $uids = array_unique($uids);
        $result = $this->get_user_role_dao()->find_by_ids($uids);
        if(!empty($result)) {
            apf_require_class('Bll_Attendance_Role');
            $bll_role = new Bll_Attendance_Role();
            $all_role = $bll_role->get_all_role();
            foreach($result as $key=>$v) {
                $role_name = $all_role[$v['role_id']]['name'];
                $result[$key]['role_name'] = $role_name;
            }
        }
        return $result;
    }

    /**
     *搜索用户 移植于 Bll_Login_User
     */
    public function search_userinfo($where,$order = null,$limit = 0,$offset = 0) {
       if(!empty($where['role_id'])) {
           $_where = array('role_id'=>(int)$where['role_id']);
           $_where['search_keywords'] = $where['search_keywords'];
           if(!empty($where['city_name'])) {
               $_where['city_name'] = $where['city_name'];
               $total = $this->get_user_role_dao()->_find_count($_where);
               $_rs = $this->get_user_role_dao()->_find_short_assoc($_where,"user_id asc",$limit,$offset);
           }else {
               $total = $this->get_user_role_dao()->_find_count($_where);
               $_rs = $this->get_user_role_dao()->_find_short_assoc($_where,"user_id asc",$limit,$offset);
           }
           if(empty($_rs)) {return array();}
           $_userids = array();
           foreach($_rs as $v) {
             $_userids[] = $v['user_id'];
           }
           $in_list = implode(',',$_userids);
           $where["user_id in ($in_list) and 1=?"] = '1';
           unset($where['role_id']);
           $offset = 0;
       }
       unset($where['search_keywords']);
       $where['dimission_date'] = '0000-00-00 00:00:00';
       if(!isset($total)) {
          $total = $this->get_userinfo_dao()->find_count($where);
       }

       $rs = $this->get_userinfo_dao()->find_short_assoc($where,$order,$limit,$offset);
       $userids = array();
       foreach((array)$rs as $key => $v) {
          $userids[] = $v['user_id'];
          $rs[$key]['indue_date'] = substr($v['indue_date'],0,10);
       }

       if(!empty($rs)) {
           //获得用户角色
           $user_list = $this->get_user_role($userids);
           foreach($rs as $key => $v) {
                $role_name = $user_list[$v['user_id']]['role_name'];
                $rs[$key]['role_name'] = empty($role_name) ? '普通员工':$role_name;
           }
       }

        return array('data'=>$rs,'total'=>$total);
    }

    /**
     * 搜索下属信息 移植于 Bll_Login_User
     */
    public function search_subordinate_userinfo($where,$order = null,$limit = 0,$offset = 0) {
        $result = array();
        if(empty($where['superior_id'])) {
            return $result;
        }
        if(empty($where['level'])) {
            $where['level'] = '1';
        }
        if($where['level']=='all') {
            unset($where['level']);
        }
        $rs = $this->get_orgRelation_dao()->_find_short_assoc($where,$order,$limit,$offset);
        $total = $this->get_orgRelation_dao()->_find_count($where);
        return array('data'=>$rs,'total'=>$total);
    }

    /**
     * 搜索所有用户信息 for HR 移植于 Bll_Login_User
     */
    public function search_subordinate_userinfo_hr($where,$order = null,$limit = 0,$offset = 0) {
        $this->session_act();
        $result = array();
        $rs = $this->get_orgRelation_dao()->_find_short_assoc_hr($where,$order,$limit,$offset);
        $total = $this->get_orgRelation_dao()->_find_count_hr($where);
        return array('data'=>$rs,'total'=>$total);
    }


    /**
     * 搜索下属报表导出 移植于 Bll_Login_User
     */
    public function search_subordinate_exp_userinfo($where,$order = null) {
        $result = array();
        if(empty($where['superior_id'])) {
            return $result;
        }
        if(empty($where['level'])) {
            $where['level'] = '1';
        }
        if($where['level']=='all') {
            unset($where['level']);
        }
        $total = $this->get_org_relation_dao()->_find_count($where);
        $rs = $this->get_org_relation_dao()->_find_short_assoc($where,$order,$total,0);
        return array('data'=>$rs,'total'=>$total);
    }

    /**
     * 搜索下属报表导出 HR 移植于 Bll_Login_User
     */
    public function search_subordinate_exp_userinfo_hr($where,$order = null) {
        $result = array();
        $total = $this->get_org_relation_dao()->_find_count_hr($where);
        $rs = $this->get_org_relation_dao()->_find_short_assoc_hr($where,$order,$total,0);
        return array('data'=>$rs,'total'=>$total);
    }
    /**
     * 获取所有销售人员和非上海人员
     */
    public function get_sale_and_not_in_shanghai(){
        return $this->get_app_dao()->get_sale_and_not_in_shanghai();
    }
    /**
     * 特殊班别的用户
     */
    public function get_all_special_work_user(){
        $res=array();
        $data = $this->get_app_dao()->find(array('user_type'=>1));
        if(empty($data)){
            return $res;
        }
        foreach($data as $val){
            $res[$val['user_id']]=$val['user_type_date'];
        }
        return $res;
    }
    /**
     * @return Dao_Attendance_LeaveRecord
     */
    private function get_app_dao(){
        return $this->get_dao('Dao_Attendance_UserInfo');
    }

    private function get_department_dao(){
        return $this->get_dao("Dao_Attendance_Department");
    }
     /**
     * @return DAO_Attendance_UserRole
     */
    private function get_user_role_dao(){
        $dao = $this->get_dao('DAO_Attendance_UserRole');
        return $dao;
    }

    /**
     * @return Dao_Attendance_LeaveRecord
     */
    private function get_leave_record_dao() {
        $dao = $this->get_dao('Dao_Attendance_LeaveRecord');
        return $dao;
    }
    private function get_orgRelation_dao() {
        $dao = $this->get_dao('Dao_Attendance_OrgRelation');
        return $dao;
    }
}
